﻿<script lang="ts" name="goodsModel" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, type UploadProps, type UploadFile } from "element-plus";
import type { FormRules } from "element-plus";
import { formatDate } from '/@/utils/formatTime';
import { useGoodsModelApi } from '/@/api/Goods/Details/goodsModel';
import { useGoodsTypeModelApi } from '/@/api/Goods/goodsTypeModel';
import { useSyssupplierApi } from '/@/api/interacting/syssupplier';
import { useSyscustomerApi } from '/@/api/interacting/syscustomer';
import { useWarehouseModelApi } from '/@/api/interacting/warehouse/warehouseModel';
import { getDictDataList } from '/@/api/system/admin';
import { getAPI } from '/@/utils/axios-utils';
import { SysFileApi } from '/@/api-services/api';

//父级传递来的函数，用于回调
const emit = defineEmits(["reloadTable"]);
const goodsModelApi = useGoodsModelApi();
const goodsTypeModelApi = useGoodsTypeModelApi();
const syssupplierApi = useSyssupplierApi();
const syscustomerApi = useSyscustomerApi();
const warehouseModelApi = useWarehouseModelApi();
const ruleFormRef = ref();
const uploadRef = ref();

const state = reactive({
	title: '',
	loading: false,
	showDialog: false,
	ruleForm: {} as any,
	stores: {},
	dropdownData: {} as any,
	goodsTypeList: [] as any[], // 货品类型列表
	goodsTypeTreeData: [] as any[], // 货品类型树形数据
	supplierList: [] as any[], // 供应商列表
	customerList: [] as any[], // 客户列表
	goodsUnitList: [] as any[], // 货品单位列表
	warehouseList: [] as any[], // 仓库列表
	imageUrl: '', // 图片预览URL
	uploadLoading: false, // 上传loading状态
});

// 自行添加其他规则
const rules = ref<FormRules>({
	goodsCode: [{ required: true, message: '请选择货品编码！', trigger: 'blur', },],
	goodsName: [{ required: true, message: '请选择货品名称！', trigger: 'blur', },],
	goodsType: [{ required: true, message: '请选择货品状态！', trigger: 'blur', },],
	goodsExpiration: [{ required: true, message: '请选择保质期管理！', trigger: 'blur', },],
});

// 构建树形数据结构
const buildTreeData = (list: any[]) => {
	// 创建映射表
	const map = new Map();
	const roots: any[] = [];

	// 首先创建所有节点
	list.forEach(item => {
		map.set(item.id, {
			value: item.id,
			label: `${item.goodsTypeCode} - ${item.goodsTypeName}`,
			id: item.id,
			goodsParentId: item.goodsParentId,
			children: []
		});
	});

	// 然后建立父子关系
	list.forEach(item => {
		const node = map.get(item.id);
		if (item.goodsParentId && map.has(item.goodsParentId)) {
			// 有父节点，添加到父节点的children中
			const parent = map.get(item.goodsParentId);
			parent.children.push(node);
		} else {
			// 没有父节点或父节点不存在，作为根节点
			roots.push(node);
		}
	});

	// 清理空的children数组
	const cleanEmptyChildren = (nodes: any[]) => {
		nodes.forEach(node => {
			if (node.children && node.children.length === 0) {
				delete node.children;
			} else if (node.children && node.children.length > 0) {
				cleanEmptyChildren(node.children);
			}
		});
	};
	cleanEmptyChildren(roots);

	return roots;
};

// 页面加载时
onMounted(async () => {
	// 加载货品类型列表
	try {
		const res = await goodsTypeModelApi.page({ page: 1, pageSize: 9999 });
		state.goodsTypeList = res.data.result?.items || [];
		// 构建树形结构
		state.goodsTypeTreeData = buildTreeData(state.goodsTypeList);
		console.log('货品类型列表数据:', state.goodsTypeList);
		console.log('货品类型树形数据:', state.goodsTypeTreeData);
	} catch (_error) {
		console.error('加载货品类型列表失败:', _error);
	}

	// 加载供应商列表
	try {
		const res = await syssupplierApi.page({ page: 1, pageSize: 9999 });
		state.supplierList = res.data.result?.items || [];
		console.log('供应商列表数据:', state.supplierList);
	} catch (_error) {
		console.error('加载供应商列表失败:', _error);
	}

	// 加载客户列表
	try {
		const res = await syscustomerApi.page({ page: 1, pageSize: 9999 });
		state.customerList = res.data.result?.items || [];
		console.log('客户列表数据:', state.customerList);
	} catch (_error) {
		console.error('加载客户列表失败:', _error);
	}

	// 加载货品单位列表（从字典数据）
	try {
		const res = await getDictDataList('GoodsEnumm');
		console.log('货品单位API完整响应:', res);
		// 字典数据可能在 result 或 data 中
		const dictData = res.data?.result || res.data || [];
		console.log('货品单位原始数据:', dictData);
		// 确保数据格式正确，过滤掉null或undefined的项，并打印每一项
		state.goodsUnitList = Array.isArray(dictData) 
			? dictData.filter(item => {
				console.log('字典项:', item);
				return item && (item.value !== null && item.value !== undefined);
			})
			: [];
		console.log('货品单位最终列表数据:', state.goodsUnitList);
	} catch (_error) {
		console.error('加载货品单位列表失败:', _error);
		state.goodsUnitList = [];
	}

	// 加载仓库列表
	try {
		const res = await warehouseModelApi.page({ page: 1, pageSize: 9999 });
		state.warehouseList = res.data.result?.items || [];
		console.log('仓库列表数据:', state.warehouseList);
	} catch (_error) {
		console.error('加载仓库列表失败:', _error);
	}
});

// 自动生成货品编码
const generateGoodsCode = async () => {
	try {
		// 获取所有货品数据
		const res = await goodsModelApi.page({ page: 1, pageSize: 9999 });
		const goods = res.data.result?.items || [];

		// 找出所有以GD开头的编码
		const gdCodes = goods
			.map((item: any) => item.goodsCode)
			.filter((code: string) => code && code.startsWith('GD'))
			.map((code: string) => {
				const num = parseInt(code.substring(2));
				return isNaN(num) ? 0 : num;
			});

		// 获取最大数字，没有则从0开始
		const maxNum = gdCodes.length > 0 ? Math.max(...gdCodes) : 0;

		// 生成新编码：GD + 4位数字（补零）
		const newNum = maxNum + 1;
		state.ruleForm.goodsCode = 'GD' + newNum.toString().padStart(4, '0');

		ElMessage.success('编码生成成功');
	} catch (_error) {
		ElMessage.error('编码生成失败');
	}
};

// 图片上传前的钩子
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
	const isImage = rawFile.type.startsWith('image/');
	const isLt5M = rawFile.size / 1024 / 1024 < 5;

	if (!isImage) {
		ElMessage.error('只能上传图片文件！');
		return false;
	}
	if (!isLt5M) {
		ElMessage.error('图片大小不能超过 5MB！');
		return false;
	}
	return true;
};

// 图片上传
const handleUploadChange: UploadProps['onChange'] = async (uploadFile: UploadFile) => {
	if (uploadFile.raw) {
		try {
			state.uploadLoading = true;
			// 上传到后端
			const res = await getAPI(SysFileApi).apiSysFileUploadFilePostForm(
				uploadFile.raw,
				'货品图片',
				true, // 公开访问
				'.jpg,.jpeg,.png,.gif,.bmp'
			);

			if (res.data.result) {
				const fileInfo = res.data.result;
				// 保存文件信息（根据存储方式保存不同内容）
				if (fileInfo.bucketName === 'Local') {
					// 本地存储：保存完整路径
					state.ruleForm.goodsPic = `${fileInfo.filePath}/${fileInfo.id}${fileInfo.suffix}`;
				} else if (fileInfo.url) {
					// 云存储：保存完整URL
					state.ruleForm.goodsPic = fileInfo.url;
				} else {
					// 默认保存ID
					state.ruleForm.goodsPic = fileInfo.id?.toString();
				}
				// 设置预览URL
				state.imageUrl = getFileUrl(fileInfo);
				ElMessage.success('图片上传成功');
			}
		} catch (error) {
			console.error('图片上传失败:', error);
			ElMessage.error('图片上传失败');
		} finally {
			state.uploadLoading = false;
		}
	}
};

// 删除图片
const handleRemoveImage = () => {
	state.ruleForm.goodsPic = '';
	state.imageUrl = '';
	if (uploadRef.value) {
		uploadRef.value.clearFiles();
	}
};

// 获取文件URL
const getFileUrl = (file: any) => {
	if (!file) return '';
	// 如果file是字符串（文件ID），需要先判断存储方式
	if (typeof file === 'string' || typeof file === 'number') {
		// 直接使用文件ID构建URL（本地存储方式）
		return `/${file}`;
	}
	// 如果file是对象，根据存储位置构建URL
	if (file.bucketName === 'Local') {
		return `/${file.filePath}/${file.id}${file.suffix}`;
	} else if (file.url) {
		// 其他存储方式（如OSS），直接使用返回的URL
		return file.url;
	}
	// 默认使用ID访问
	return `/${file.id}`;
};

// 解析保质期数据（将varchar64格式拆分为数字和单位）
const parseExpirationData = (expirationStr: string) => {
	if (!expirationStr) return { num: '', unit: '' };
	
	// 匹配数字和单位的正则表达式
	const match = expirationStr.match(/^(\d+)([天月年])$/);
	if (match) {
		return {
			num: match[1],
			unit: match[2]
		};
	}
	
	// 如果不匹配标准格式，尝试其他可能的格式
	const numMatch = expirationStr.match(/\d+/);
	const unitMatch = expirationStr.match(/[天月年]/);
	
	return {
		num: numMatch ? numMatch[0] : expirationStr,
		unit: unitMatch ? unitMatch[0] : ''
	};
};

// 合并保质期数据（将数字和单位合并为varchar64格式）
const combineExpirationData = (num: string, unit: string) => {
	if (!num) return '';
	if (!unit) return num;
	return `${num}${unit}`;
};

// 打开弹窗
const openDialog = async (row: any, title: string) => {
	state.title = title;
	row = row ?? {};
	
	// 如果是编辑，加载详情数据；如果是新增，使用空对象
	if (row.id) {
		// 编辑模式：从服务器加载完整数据
		state.ruleForm = await goodsModelApi.detail(row.id).then(res => res.data.result);
		
		// 解析保质期数据
		if (state.ruleForm.goodsExpirationNum) {
			const parsed = parseExpirationData(state.ruleForm.goodsExpirationNum);
			state.ruleForm.goodsExpirationNum = parsed.num;
			state.ruleForm.goodsExpirationUnit = parsed.unit;
		}
	} else {
		// 新增模式：初始化默认值
		state.ruleForm = {
			...JSON.parse(JSON.stringify(row)),
			goodsType: true,  // 货品状态默认为启用
			goodsExpiration: false,  // 保质期管理默认为否
			goodsExpirationNum: '',  // 保质期数字
			goodsExpirationUnit: '',  // 保质期单位
		};
	}

	// 设置图片预览URL
	if (state.ruleForm.goodsPic) {
		// goodsPic可能是文件路径、URL或ID
		state.imageUrl = state.ruleForm.goodsPic.startsWith('http') || state.ruleForm.goodsPic.startsWith('/')
			? state.ruleForm.goodsPic
			: `/${state.ruleForm.goodsPic}`;
	} else {
		state.imageUrl = '';
	}

	// 重新加载货品类型列表（确保数据是最新的）
	try {
		const res = await goodsTypeModelApi.page({ page: 1, pageSize: 9999 });
		state.goodsTypeList = res.data.result?.items || [];
		state.goodsTypeTreeData = buildTreeData(state.goodsTypeList);
	} catch (_error) {
		console.error('加载货品类型列表失败:', _error);
	}

	state.showDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
	emit("reloadTable");
	state.showDialog = false;
};

// 提交
const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			let values = { ...state.ruleForm };
			
			// 合并保质期数据
			if (values.goodsExpirationNum || values.goodsExpirationUnit) {
				values.goodsExpirationNum = combineExpirationData(
					values.goodsExpirationNum || '', 
					values.goodsExpirationUnit || ''
				);
			}
			
			// 删除临时的单位字段，避免提交到后端
			delete values.goodsExpirationUnit;
			
			console.log('提交的数据:', values);
			await goodsModelApi[state.ruleForm.id ? 'update' : 'add'](values);
			closeDialog();
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: "error",
			});
		}
	});
};

//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
<template>
	<div class="goodsModel-container">
		<el-dialog v-model="state.showDialog" :width="800" draggable :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<span>{{ state.title }}</span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="state.ruleForm.id" />
					</el-form-item>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="货品编码" prop="goodsCode">
							<div style="display: flex; gap: 8px;">
								<el-input v-model="state.ruleForm.goodsCode" placeholder="货品编码将自动生成" maxlength="64"
									show-word-limit readonly />
								<el-button type="primary" size="default" @click="generateGoodsCode" :icon="'Refresh'">
									自动生成
								</el-button>
							</div>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="货品名称" prop="goodsName">
							<el-input v-model="state.ruleForm.goodsName" placeholder="请输入货品名称" maxlength="128"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="货品类型" prop="goodsTypeId">
							<el-tree-select v-model="state.ruleForm.goodsTypeId" :data="state.goodsTypeTreeData"
								placeholder="请选择货品类型" clearable filterable check-strictly :render-after-expand="false"
								style="width: 100%" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="货品规格型号" prop="goodsSpecs">
							<el-input v-model="state.ruleForm.goodsSpecs" placeholder="请输入货品规格型号" maxlength="128"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="供应商" prop="goodsSupplierId">
							<el-select v-model="state.ruleForm.goodsSupplierId" clearable filterable
								placeholder="请选择供应商">
								<el-option v-for="item in state.supplierList" :key="item.id" :label="item.name"
									:value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="客户" prop="goodsCustomerId">
							<el-select v-model="state.ruleForm.goodsCustomerId" clearable filterable
								placeholder="请选择客户">
								<el-option v-for="item in state.customerList" :key="item.id" :label="item.customerName"
									:value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="入库参考价/元" prop="goodsIntoMoney">
							<el-input-number v-model="state.ruleForm.goodsIntoMoney" placeholder="请输入入库参考价/元"
								clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="出库参考价/元" prop="goodsOutMoney">
							<el-input-number v-model="state.ruleForm.goodsOutMoney" placeholder="请输入出库参考价/元"
								clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="货品状态" prop="goodsType">
							<el-switch v-model="state.ruleForm.goodsType" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="保质期管理" prop="goodsExpiration">
							<el-switch v-model="state.ruleForm.goodsExpiration" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="state.ruleForm.goodsExpiration">
						<el-form-item label="保质期" prop="goodsExpirationNum">
							<div style="display: flex; gap: 8px;">
								<el-input 
									v-model="state.ruleForm.goodsExpirationNum" 
									placeholder="请输入保质期" 
									maxlength="64"
									show-word-limit 
									clearable 
									style="flex: 1;"
								/>
								<el-select 
									v-model="state.ruleForm.goodsExpirationUnit" 
									placeholder="单位"
									style="width: 80px;"
									clearable
								>
									<el-option label="天" value="天" />
									<el-option label="月" value="月" />
									<el-option label="年" value="年" />
								</el-select>
							</div>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="state.ruleForm.goodsExpiration">
						<el-form-item label="预警天数" prop="goodsWarning">
							<el-input-number v-model="state.ruleForm.goodsWarning" placeholder="请输入预警天数" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="货品备注" prop="goodsNote">
							<el-input v-model="state.ruleForm.goodsNote" placeholder="请输入货品备注" maxlength="512"
								show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="货品单位" prop="goodsUnitId">
							<el-select v-model="state.ruleForm.goodsUnitId" clearable filterable placeholder="请选择货品单位">
								<el-option v-for="item in state.goodsUnitList"
									:label="item?.label" :value="item?.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="货品图片" prop="goodsPic">
							<el-upload ref="uploadRef" class="avatar-uploader" action="#" :show-file-list="false"
								:auto-upload="false" :before-upload="beforeUpload" :on-change="handleUploadChange"
								accept="image/*" :disabled="state.uploadLoading">
								<el-image v-if="state.imageUrl" :src="state.imageUrl" class="avatar" fit="contain"
									:preview-src-list="[state.imageUrl]" :preview-teleported="true"
									style="width: 148px; height: 148px; border: 1px dashed #d9d9d9; border-radius: 6px;" />
								<el-icon v-else class="avatar-uploader-icon" :size="50"
									style="width: 148px; height: 148px; border: 1px dashed #d9d9d9; border-radius: 6px; display: flex; align-items: center; justify-content: center;">
									<ele-Plus v-if="!state.uploadLoading" />
									<ele-Loading v-else class="is-loading" />
								</el-icon>
							</el-upload>
							<div style="margin-top: 8px;">
								<el-button v-if="state.imageUrl" size="small" type="danger" @click="handleRemoveImage"
									icon="ele-Delete">删除图片</el-button>
								<div style="color: #999; font-size: 12px; margin-top: 4px;">支持 jpg、png、gif、bmp 格式，大小不超过
									5MB</div>
							</div>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="货品仓库" prop="goodsWareId">
							<el-select v-model="state.ruleForm.goodsWareId" clearable filterable placeholder="请选择货品仓库">
								<el-option v-for="item in state.warehouseList" :key="item.id" :label="item.wareName"
									:value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="() => state.showDialog = false">取 消</el-button>
					<el-button @click="submit" type="primary" v-reclick="1000">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>